package com.yyfax.ph.personal.update;

import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.ph.Global;
import com.yyfax.ph.base.YJPH;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class UpdatePresenter extends Presenter<UpdateModel, UpdatePresenter.View> {
	private static final String TAG = UpdatePresenter.class.getSimpleName();

	public static class Generator implements PresenterFactory<UpdatePresenter> {
		@Override
		public UpdatePresenter create() {
			return new UpdatePresenter();
		}
	}

	public interface View extends IView {
		void hasNewVersion(boolean forceUpdate, String url, String content, String title);

		void isNewestVersion();

		void checkNewVersionFailed();
	}

	private View mView;

	private String mRequestPage;

	@Override
	public void attach(View view) {
		mRequestPage = view.getClass().getName();
		mView = view;
		mModel = new UpdateModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public void checkUpdate() {
		CLog.i(TAG, "UpdatePresenter.checkUpdate()");
		execute(null, FUNCTIONAL_CODE, false, null, mRequestPage);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void checkUpdateResult(UpdateModel.UpdateResult result) {
		CLog.i(TAG, result.toString());
		if (mRequestPage.equals(result.requestPage) && result.getContent() != null) {
			UpdateModel.UpdateBean bean = result.getContent();
			String configVersion = bean.configVersion;
			if (!"1".equals(configVersion) || !Global.SOURCE.equals(bean.type)) {//判断配置版本信息和平台
				mView.isNewestVersion();
				return;
			}
			boolean enableAll = 1 == bean.enableAll;
			List<String> channelList = bean.channels;
			if (!enableAll && !channelList.contains(YJPH.channel)) {
				mView.isNewestVersion();
				return;
			}
			int remoteVersionCode = bean.versionCode;
			if (remoteVersionCode > YJPH.versionCode) {
				String url = bean.url;
				int status = bean.yesNo;
				String remoteVersion = bean.version;
				//需要强制更新
				if (status == 1) {
					mView.hasNewVersion(true, url, bean.content, "V " + remoteVersion + "新版本更新:");
				}
				//非强制更新
				else if (status == 0) {
					mView.hasNewVersion(false, url, bean.content, "V " + remoteVersion + "新版本更新:");
				}
			} else {
				mView.isNewestVersion();
			}
		} else {
			mView.checkNewVersionFailed();
		}
	}
}
